package org.dolphin.dao.impl;

import java.util.Date;
import java.util.List;
import java.util.Set;
import org.dolphin.dao.GroupDao;
import org.dolphin.dao.util.SessionHelper;
import org.dolphin.entity.security.Group;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository(value = "groupDao")
public class GroupDaoImpl implements GroupDao {
  @Autowired(required = true)
  private SessionFactory sessionFactory;

  @Override
  public void createGroup(Group group) {
    Session session = SessionHelper.getCurrentSession(sessionFactory);
    group.setCreatedDate(new Date());
    session.save(group);
  }

  @SuppressWarnings("unchecked")
  @Override
  public List<Group> getAssignedGroups(String username) {
    DetachedCriteria dc = DetachedCriteria.forClass(Group.class);
    dc.createAlias("users", "users");
    dc.add(Restrictions.eq("users.username", username));
    Session session = SessionHelper.getCurrentSession(sessionFactory);
    List<Group> list = dc.getExecutableCriteria(session).list();
    return list;
  }

  @SuppressWarnings("unchecked")
  @Override
  public Group loadGroup(String groupName) {
    DetachedCriteria dc = DetachedCriteria.forClass(Group.class);
    dc.add(Restrictions.eq("name", groupName));
    Session session = SessionHelper.getCurrentSession(sessionFactory);
    List<Group> list = dc.getExecutableCriteria(session).list();
    if (list != null && !list.isEmpty()) {
      return list.get(0);
    }
    return null;
  }

  @SuppressWarnings("unchecked")
  @Override
  public List<Group> loadGroups(Set<String> groupName) {
    DetachedCriteria dc = DetachedCriteria.forClass(Group.class);
    dc.add(Restrictions.in("name", groupName));
    Session session = SessionHelper.getCurrentSession(sessionFactory);
    List<Group> list = dc.getExecutableCriteria(session).list();
    return list;
  }
}
